package com.lzp.test;


import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.*;
import java.net.MalformedURLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;

/**
 * @author : lzp
 * @version 1.0
 * @date : 2021/12/4 16:16
 * @apiNote : TODO
 */
public class PngToPdf {
    public static void main(String[] args) {
        //File file=new File("C:\\Users\\lzp\\Pictures\\指纹.png");
        //String reg=".+((?i).jpeg|.jpg|.png)$";
        //Pattern pattern = Pattern.compile(reg);
        //Matcher matcher = pattern.matcher("1.jPG");
        //System.out.println(matcher.find());
        //System.out.println(matcher.matches());

        ////base64转pdf
        //String source = "C:\\Users\\lzp\\Desktop\\base64图片.txt";
        //try {
        //    BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(source)));
        //    StringBuffer sb = new StringBuffer();
        //    String str;
        //    while ((str = reader.readLine()) != null) {
        //        sb.append(str);
        //    }
        //    String string = sb.toString();
        //    if (string.contains("base64")) {
        //        String[] split = string.split(",");
        //        int strat = split[0].indexOf("/") + 1;
        //        int end = split[0].indexOf(";");
        //        String fileType = split[0].substring(strat, end);
        //        String fullImgUrl = "C:\\Users\\lzp\\Desktop\\base64图片2号." + fileType;
        //
        //        BASE64Decoder decoder = new BASE64Decoder();
        //        File file = new File(fullImgUrl);
        //
        //        if (!file.exists() && !file.isDirectory()) {
        //            File file1 = new File(file.getParent());
        //            if (!file1.exists()) {
        //                file1.mkdirs();
        //            }
        //        }
        //        FileOutputStream fos = new FileOutputStream(file);
        //        byte[] bytes = decoder.decodeBuffer(split[1]);
        //        fos.write(bytes);
        //        fos.close();
        //    }
        //} catch (FileNotFoundException e) {
        //    e.printStackTrace();
        //} catch (IOException e) {
        //    e.printStackTrace();
        //}
        //合成pdf测试
        List<String> strings = new ArrayList<>();
        strings.add("C:\\Users\\lzp\\Desktop\\3.pdf");
        strings.add("C:\\Users\\lzp\\Desktop\\3.pdf");
        strings.add("C:\\Users\\lzp\\Desktop\\忘记打卡签卡操作说明.pdf");
        //strings.add(fullImgUrl);
        String targetUrl = "C:\\Users\\lzp\\Desktop\\3.pdf";
        File file1 = new File(targetUrl);
        File file2 = new File(file1.getParent());
        if (!file2.exists()) {
            file2.mkdirs();
        }
        //convert(strings, targetUrl);
        try {
            synthesisPdf(strings, targetUrl);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

    /**pdf合成
     * @param pdfUrlList url集合,第一张pdf大小作为目标pdf大小
     * @param target 目标url
     * @throws IOException
     * @throws DocumentException
     */
    private static void synthesisPdf(List<String> pdfUrlList, String target) throws IOException, DocumentException {
        //获取第一个pdf的文档大小作为目标pdf的大小
        Document document = new Document(new PdfReader(pdfUrlList.get(0)).getPageSize(1));
        FileOutputStream targetOs = new FileOutputStream(target);
        PdfCopy copy=new PdfCopy(document,targetOs);
        document.open();
        for (String pdfUrl : pdfUrlList) {
            PdfReader reader = new PdfReader(pdfUrl);
            int numberOfPages = reader.getNumberOfPages();
            for (int i = 1; i <= numberOfPages; i++) {
                document.newPage();
                PdfImportedPage page=copy.getImportedPage(reader,i);
                copy.addPage(page);
            }
        }
        copy.close();
        targetOs.close();
        document.close();
    }

    /** 所有图片合成一个pdf
     * @param sourceList 图片urlList
     * @param target 目标pdf路径
     */
    public static void convert(List<String> sourceList, String target) {
        Document document = new Document();
        // 设置文档页边距
        document.setMargins(0, 0, 0, 0);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(target);
            PdfWriter.getInstance(document, fos);
            // 打开文档
            document.open();
            for (String source : sourceList) {
                // 获取图片的宽高
                Image image = Image.getInstance(source);
                float imageHeight = image.getScaledHeight();
                float imageWidth = image.getScaledWidth();
                // 设置页面宽高与图片一致
                Rectangle rectangle = new Rectangle(imageWidth, imageHeight);
                document.setPageSize(rectangle);
                // 图片居中
                image.setAlignment(Image.ALIGN_CENTER);
                // 新建一页添加图片
                document.newPage();
                document.add(image);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (BadElementException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        } finally {
            // 关闭文档
            document.close();
        }
    }

    private static String replaceSuffix(String fullUrl) {
        String fullImgUrl = copyInSameFolder(fullUrl);
        assert fullImgUrl != null;
        String filePath = fullImgUrl.substring(0, fullImgUrl.lastIndexOf(File.separator) + 1);
        String fileName = fullImgUrl.substring(fullImgUrl.lastIndexOf(File.separator) + 1);

        String[] split = fileName.split("\\.");
        assert split.length == 2;
        String pdfFileName = split[0] + ".pdf";
        return filePath + pdfFileName;
    }

    /**
     * 同一文件夹下复制文件
     *
     * @param srcPathStr 要复制的文件路径
     * @return 新文件的全路径名
     */
    public static String copyInSameFolder(String srcPathStr) {
        String filePath = srcPathStr.substring(0, srcPathStr.lastIndexOf(File.separator) + 1);
        String fileName = srcPathStr.substring(srcPathStr.lastIndexOf(File.separator) + 1);

        String[] split = fileName.split("\\.");
        String uuidFileName = randomFileName() + "." + split[split.length - 1];
        //目标文件路径
        String targetFileName = filePath + uuidFileName;

        Boolean success = copyFile(srcPathStr, targetFileName);
        if (success) {
            return targetFileName;
        }
        return null;
    }

    /** 生成有规律的随机数字,可以用来当文件名
     * @return 当前时间+随机uuid哈希值的字符串
     */
    public static String randomFileName() {
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String format = dateFormat.format(new Date());
        int uuidHashValue = UUID.randomUUID().toString().hashCode();
        return format + (uuidHashValue < 0 ? -uuidHashValue : uuidHashValue);
    }

    /** 复制文件
     * @param srcPath    原文件路径
     * @param targetPath 目标文件路径
     * @return 是否复制成功
     */
    public static Boolean copyFile(String srcPath, String targetPath) {
        try (FileInputStream fis = new FileInputStream(srcPath);
             FileOutputStream fos = new FileOutputStream(targetPath)) {
            byte[] bytes = new byte[1024 * 8];
            int len;
            while ((len = fis.read(bytes)) != -1) {
                fos.write(bytes, 0, len);
            }
        } catch (Exception e) {
            return false;
        }
        return true;
    }
}
